<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HugeCSV</title>
    <!-- 引入Vue和Element UI -->
    <script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
    <h1>HugeCSV Page</h1>
    <p>This is the HugeCSV page.</p>
    <!-- 添加返回首页的按钮 -->
    <button id="backButton">返回首页</button>
    <!-- 添加创建SQLite数据库的按钮 -->
    <button id="createDBButton">创建SQLite数据库</button>
    <!-- 添加选择CSV文件的按钮 -->
    <button id="selectCSVButton">选择CSV文件</button>
    <input type="file" id="csvFileInput" accept=".csv" style="display: none;">
    <textarea id="statusText" rows="10" cols="80" style="margin-top: 20px; width: 80%;" readonly>
请选择CSV文件开始导入
    </textarea>
    <div id="dataContainer" style="margin-top: 20px;"></div>
    <div id="pagination" style="margin-top: 20px; display: flex; gap: 8px;">
        <button id="prevPage" disabled>上一页</button>
        <span id="pageInfo"></span>
        <button id="nextPage" disabled>下一页</button>
    </div>

    <script>
        // 获取按钮元素
        const backButton = document.getElementById('backButton');
        const createDBButton = document.getElementById('createDBButton');

        // 为按钮添加点击事件监听器
        backButton.addEventListener('click', () => {
            window.history.back();
        });

        createDBButton.addEventListener('click', () => {
            createSQLiteDatabase();
        });

        // 获取选择CSV文件按钮和输入元素
        const selectCSVButton = document.getElementById('selectCSVButton');
        const csvFileInput = document.getElementById('csvFileInput');
        const statusText = document.getElementById('statusText');

        // 为选择CSV文件按钮添加点击事件
        selectCSVButton.addEventListener('click', () => {
            csvFileInput.click();
        });

        // 处理文件选择
        csvFileInput.addEventListener('change', (event) => {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = async (e) => {
                    const text = e.target.result;
                    const lines = text.split('\n');
                    const headers = lines[0].split(',');
                    
                    // 更新状态
                    statusText.value = '正在读取CSV文件...\n';
                    statusText.value += 'CSV文件前10行内容:\n';
                    lines.slice(0, 10).forEach((line, index) => {
                        statusText.value += `${index + 1}: ${line}\n`;
                    });

                    // 发送CSV数据到主进程进行插入
                    try {
                        statusText.value += '正在清空旧数据...\n';
                        statusText.value += '正在导入新数据...\n';
                        const result = await ipcRenderer.invoke('import-csv-data', {
                            headers: headers,
                            lines: lines.slice(1)
                        });
                        statusText.value += `\nCSV数据导入完成\n`;
                        statusText.value += `总行数: ${lines.length}\n`;
                        statusText.value += `成功导入: ${result.insertedCount}行\n`;
                        statusText.value += `跳过/失败: ${lines.length - result.insertedCount}行\n`;
                        if (result.errors && result.errors.length > 0) {
                            statusText.value += `错误详情:\n${result.errors.slice(0, 10).join('\n')}\n`;
                            if (result.errors.length > 10) {
                                statusText.value += `(显示前10个错误，共${result.errors.length}个错误)\n`;
                            }
                        }
                    } catch (error) {
                        statusText.value += `错误: ${error.message}\n`;
                    }
                };
                reader.readAsText(file);
            }
        });

        const { ipcRenderer } = require('electron');

        // 打开数据库连接
        function openDatabase() {
            return ipcRenderer.invoke('open-database');
        }

        // 定义函数来创建SQLite数据库
        function createSQLiteDatabase() {
            ipcRenderer.invoke('create-database').then(result => {
                statusText.value += result.message + '\n';
            }).catch(error => {
                statusText.value += `错误: ${error.message}\n`;
            });
        }

        // 分页设置
        const PAGE_SIZE = 50; // 每页显示50条数据

        // 获取并显示分页数据
        async function loadData(page = 1) {
            try {
                const dataContainer = document.getElementById('dataContainer');
                dataContainer.innerHTML = ''; // 清空旧数据
                
                const result = await ipcRenderer.invoke('get-csv-data', { page });
                app.totalCount = result.totalCount;
                
                // 显示数据
                result.data.forEach((row, index) => {
                    const div = document.createElement('div');
                    div.className = 'data-row';
                    const rowNumber = (page - 1) * PAGE_SIZE + index + 1;
                    div.textContent = `第${rowNumber}行: ${JSON.stringify(row, null, 2)}`;
                    dataContainer.appendChild(div);
                });
            } catch (error) {
                statusText.value += `加载数据错误: ${error.message}\n`;
            }
        }

        // 初始化加载第一页数据
        loadData(app.currentPage);

        // 处理数据库操作结果
        ipcRenderer.on('database-operation', (event, message) => {
            statusText.value += message + '\n';
        });
    </script>
</body>
</html>
